<?php

namespace App\Admin\Utils;

class FlashMessage
{
    protected static $messages = [];
    protected static $statuses = ['info', 'success', 'error', 'warning'];

    /**
     * 闪存消息
     *
     * @param string $msg
     * @param string $status
     */
    public function flash($msg, $status = 'success')
    {
        if (!in_array($status, static::$statuses)) {
            $status = 'info';
        }

        if ($this->exists($msg, $status)) {
            return;
        }

        static::$messages[] = compact('msg', 'status');

        \Session::flash('flash_msg', static::$messages);
    }

    /**
     * 检查推入的消息是否已存在完全相同的
     *
     * @param string $msg
     * @param string $status
     * @return bool
     */
    protected function exists($msg, $status)
    {
        return (bool)array_first(static::$messages, function ($key, $value) use ($msg, $status) {
            return $value['msg'] == $msg && $value['status'] == $status;
        });
    }
}